package assist.datastore.parser;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import assist.datastore.JDODatastore;
import assist.datastore.dao.DAOFactory;
import assist.datastore.dao.GameDAO;
import assist.domain.model.BlockedShot;
import assist.domain.model.Event;
import assist.domain.model.EventPlayerOnIce;
import assist.domain.model.Game;
import assist.domain.model.MissedShot;
import assist.domain.model.RosterPlayer;
import assist.domain.model.ShotOnGoal;

public class NHLEventsCSVParser extends NHLCSVParser<Event>
{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Collection<EventPlayerOnIce> eventPlayersOnIce;

    public NHLEventsCSVParser(File csvFile, Integer lineNum) throws IOException
    {
        super(csvFile, lineNum);
    }

    public NHLEventsCSVParser(File csvFile, Integer lineNum, int total) throws IOException
    {
        super(csvFile, lineNum, total);
    }

    Game currentGame = null;
    @Override
    protected Event parseObject(String[] tokens)
    {
        if (eventPlayersOnIce == null)
        {
            eventPlayersOnIce = new ArrayList<EventPlayerOnIce>();
        }
        Event event = null;

        if (tokens[7].equals("SHOT") || tokens[7].equals("GOAL"))
        {
            event = new ShotOnGoal();
        }
        else if (tokens[7].equals("MISS"))
        {
            event = new MissedShot();
        }
        else if (tokens[7].equals("BLOCK"))
        {
            event = new BlockedShot();
        }        
        
        if (event == null)
        {
            return null;
        }
        event.setGameId(tokens[0] + "" + tokens[1]); 
        event.setStrength(tokens[4]);
        
        Long id = new Long(tokens[0]  + tokens[1] +  tokens[2]);
        PersistenceManager pm = JDODatastore.getPersistenceManager();
        try
        {
            Object object = pm.getObjectById(event.getClass(), id); 
            if (object != null)
            {
                System.err.println(id + "is found");
                return null;
            }
        }
        catch (Exception e)
        {
         //   System.err.println(id + "is not found");
        }
        finally
        {
         pm.close();
        }
        event.setKey(id);
        if (currentGame == null || !currentGame.getId().equals(event.getGameId()))
        {
            GameDAO gameDao = DAOFactory.getDAOFactory().getGameDAO();
            currentGame = gameDao.getById(event.getGameId());
        }
        String visTeam = currentGame.getVisitorTeamId();
       
        for (int i=9; i < 30; i+=3)
        {
            if (tokens[i].isEmpty())
            {
                break;
            }
            Integer visNum = new Integer(tokens[i]);
            EventPlayerOnIce evtPlayeOn = new EventPlayerOnIce();
            evtPlayeOn.setEventId(id);
            evtPlayeOn.setPlayerId(getPlayerId(event.getGameId(), visNum, visTeam));
            eventPlayersOnIce.add(evtPlayeOn);
        }
        String homeTeam = currentGame.getHomeTeamId();
        for (int i=42; i < 70; i+=3)
        {
            if (tokens[i].isEmpty())
            {
                break;
            }
            Integer homeNum = new Integer(tokens[i]);
            EventPlayerOnIce evtPlayeOn = new EventPlayerOnIce();
            evtPlayeOn.setEventId(id);
            Long playerId = getPlayerId(event.getGameId(), homeNum, homeTeam);
            if (playerId == null)
            {
                continue;
            }
            evtPlayeOn.setPlayerId(playerId);
            eventPlayersOnIce.add(evtPlayeOn);
        }        
        
     
        String eventTeam = tokens[8].substring(1,4);
        if (eventTeam.equals("L.A"))
        {
            eventTeam = "LAK";
        }
        else if (eventTeam.equals("T.B"))
        {
            eventTeam = "TBL";
        }
        else if (eventTeam.equals("N.J"))
        {
            eventTeam = "NJD";
        }        
        else if (eventTeam.equals("S.J"))
        {
            eventTeam = "SJS";
        }        
        if (!eventTeam.startsWith(homeTeam) && !eventTeam.startsWith(visTeam) )
        {
            System.err.println("!!!" + eventTeam);
        }
        event.setTeamId(eventTeam);
        //return null;
        return event;
    }
    Map<String, Long> playerIds;
    private Long getPlayerId(String gameId, Integer num, String team)
    {
        if (playerIds == null)
        {
            playerIds = new TreeMap<String, Long>();
        }
        Long playerId = playerIds.get(gameId + num + team);
        if (playerId != null)
        {
            return playerId;
        }
        PersistenceManager pm = JDODatastore.getPersistenceManager();
        try
        {
            Query query = pm.newQuery(RosterPlayer.class);
            query.setFilter("gamesParam == gameId && number == numParam && teamParam == team.abbreviation");
            query.declareParameters("String gamesParam, Integer numParam, String teamParam");
            query.setUnique(true);
            try
            {
            RosterPlayer rosterPlayer = 
                (RosterPlayer) query.execute(gameId, num, team);
            playerId = rosterPlayer.getPlayer().getPlayerId();
           
                playerIds.put(gameId + num + team, playerId);
                     
            }
            catch(Exception e)
            {
                System.err.println(e.getMessage());
                System.err.println("Not unique:" + gameId + team + num);
            }
            return playerId;   
            /*
            if (rosterPlayer == null)
            {
                System.err.println("RosterPlayer not found:" + gameId + team + num);
            }
            else if (rosterPlayer.getPlayer() == null)
            {
                System.err.println("RosterPlayer Player not found" + gameId + team + num);
            }  */         

        }
        finally
        {
            pm.close();
        }
    }

    public Collection<EventPlayerOnIce> getEventPlayersOnIce()
    {
        // TODO Auto-generated method stub
        return eventPlayersOnIce ;
    }

}
